package com.doodod.common.utils;

import javax.mail.*;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;
import java.io.UnsupportedEncodingException;
import java.util.Properties;

/**
 * Created by ydw on 2015/3/17 0017.
 */
public class SendMailUtil {
    private static final String DEFAULT_SMTP_HOST = "smtp.163.com";
    private static final String DEFAULT_MAIL_NAME = "ydw918@163.com";
    private static final String DEFAULT_MAIL_PASSWORD = "*******";
    private static final String DEFAULT_SEND_NAME = "ydw";

    /**
     * 系统向用户发送邮件
     *
     * @param mailTo      接收方邮箱地址
     * @param mailSubject 邮件的主题
     * @param mailText    邮件正文
     * @return 发送成功的邮件数量
     */
    public static int send(String mailTo, String mailSubject, String mailText) {

        //检查参数
        if (mailTo == null || mailSubject == null || mailText == null)
            return -1;

        //正文编码方式
        String encoding = "iso-8859-1";
        try {
            //标题不需要编码,编码后为乱码
            //正文需要编码
            mailText = new String(mailText.getBytes(), encoding);
        } catch (UnsupportedEncodingException e) {
            System.out.println("Fail to encoding mail text to " + encoding);
        }

        Properties props = new Properties();
        props.put("mail.smtp.host", DEFAULT_SMTP_HOST);//邮件服务器地址
        props.put("mail.smtp.auth", "true");
        props.put("mail.smtp.user", DEFAULT_SEND_NAME);//发送方的发送名;
        props.put("mail.smtp.from", DEFAULT_MAIL_NAME);//发送邮箱地址;
        props.put("mail.debug", "true");//不打印构建发送者信息

        //构建发送者
        Authenticator auth = new Authenticator() {
            public PasswordAuthentication getPasswordAuthentication() {
                return new PasswordAuthentication(DEFAULT_MAIL_NAME, DEFAULT_MAIL_PASSWORD);
            }
        };

        Session session = Session.getInstance(props, auth);
        session.setDebug(false);//不打印发送信息

        Message msg = new MimeMessage(session);

        try {
            msg.setRecipients(Message.RecipientType.TO, InternetAddress.parse(mailTo));//设置邮件接收地址
            msg.setSentDate(new java.util.Date());//设置邮件发送日期
            msg.setSubject(mailSubject);// 设置邮件的标题
            msg.setContent(mailText, "text/html");// 设置邮件的内容
            Transport.send(msg);//发送邮件

            return 0;
        } catch (MessagingException e) {
            System.out.println("Fail to send email for:" + e);
            return -1;
        }
    }

    public static void main(String[] args){
        SendMailUtil.send("289869876@qq.com", "ydw", "test");
    }
}
